import {
  queryMenus
} from '@/api/user'
import {
  login,
  getInfo,
  logOut
} from '@/api/login'
import {
  getToken,
  setToken,
  removeToken
} from '@/utils/auth'
import {constantRouterMap} from '@/router'

const _import = require('../../router/_import_' + process.env.NODE_ENV);

function getRoutes(data) {
  let routes = [];
  const hiddenRoutes = [];
  data.forEach((value) => {
    const menuName = value.name || '未命名';
    const path = value.url || '/';
    const component = value.component || 'layout/Layout';
    const icon = value.icon || 'system';
    const children = [];
    getChildren(value.children, children, hiddenRoutes);
    if (value.showable !== 1) {
      hiddenRoutes.push(wrapMenu(value));
    } else {
      let route;
      if (!children || children.length === 0) {
        route = wrapMenu(value);
      } else {
        route = {
          path: path,
          component: _import(component),
          name: path,
          hidden: value.showable !== 1,
          meta: {
            title: menuName,
            icon: icon
          },
          children: children,
        };
      }
      routes.push(route);
    }
  });
  routes = routes.concat(hiddenRoutes);
  return routes;
}

function getChildren(children, array, hiddenRoutes) {
  if (children) {
    children.map((value) => {
      const menuName = value.name || '未命名';
      const path = value.url || '/';
      const component = value.component || 'layout/Layout';
      const icon = value.icon || 'system';
      const children = [];
      getChildren(value.children, children, hiddenRoutes);
      if (value.showable !== 1) {
        hiddenRoutes.push(wrapMenu(value));
      } else {
        array.push({
          path: path,
          component: _import(component),
          name: path,
          hidden: value.showable !== 1,
          meta: {
            title: menuName,
            icon: icon
          },
          children: children,
          // noShowingChildren:true
        })
      }
    })
  }
}

/**
 * 一级菜单、隐藏菜单包装
 * @param m
 * @returns {
 *  {
 *    path: string,
 *    component: *,
 *    children: {
 *      path: (*|string),
 *      component: *,
 *      hidden: boolean,
 *      meta: {
 *        icon: (*|string),
 *        title: (*|string)
 *      },
 *      name: (*|string)
 *    }
 *    []
 *  }
 * }
 */
function wrapMenu(m) {
  const menuName = m.name || '未命名';
  const path = m.url || '/';
  const component = m.component || 'layout/Layout';
  const icon = m.icon || 'system';
  return {
    path: '/',
    component: _import('layout/Layout'),
    children: [{
      path: path,
      component: _import(component),
      name: path,
      hidden: m.showable !== 1,
      meta: {
        title: menuName,
        icon: icon
      },
    }],
  }
}

const user = {
  state: {
    token: getToken(),
    name: '',
    avatar: '',
    roles: [],
    mergeRoutes: constantRouterMap
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
  },

  actions: {
    // 登录 输入用户名密码返回token
    Login: function ({
                       commit
                     }, userInfo) {
      const username = userInfo.username.trim();
      return new Promise((resolve, reject) => {
        login(username, userInfo.password).then(response => {
          if (response.code === 200) {

            const data = response.data;
            setToken(data);
            commit('SET_TOKEN', data);
            resolve();
            return data;
          } else
            reject();
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo(state.token).then(response => {
          if (response.code === 200) {
            const data = response.data;
            if (data.roles && data.roles.length > 0) { // 验证返回的roles是否是一个非空数组
              commit('SET_ROLES', data.roles)
            } else {
              reject('getInfo: roles must be a non-null array !')
            }
            commit('SET_NAME', data.name);
            commit('SET_AVATAR', data.avatar || 'http://p4.music.126.net/G7GgOHBdH1rUIIW3hot6Kw==/109951163609743240.jpg?param=100y100');
            resolve(response)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    //  根据token 查询用户权限列表
    QueryMenus({
                 commit
               }) {
      return new Promise((resolve, reject) => {
        queryMenus().then(response => {
          if (response.code === 200) {
            const data = response.data;
            const addRouters = getRoutes(data);
            commit('SET_MENUS', addRouters);
            // commit('SET_AVATAR', 'http://p4.music.126.net/G7GgOHBdH1rUIIW3hot6Kw==/109951163609743240.jpg?param=100y100')
            resolve(response)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    LogOut({
             commit,
             state
           }) {
      return new Promise((resolve, reject) => {
        logOut(state.token).then(resp => {
          if (resp.code === 200) {
            commit('SET_TOKEN', '');
            commit('SET_ROLES', []);
            removeToken();
            resolve()
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({
                commit
              }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '');
        removeToken();
        resolve()
      })
    }
  }
};

export default user
